package org.embedchat.server;

import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mina.common.IoAcceptor;
import org.apache.mina.common.IoAcceptorConfig;
import org.apache.mina.transport.socket.nio.SocketAcceptor;
import org.apache.mina.transport.socket.nio.SocketAcceptorConfig;

public class Server {
	
	public static final int DEFAULT_SERVER_PORT = 49177;
	
	private static Log log = LogFactory.getLog(Server.class);
	private static final boolean USE_CUSTOM_CODEC = true;

	public boolean start() {
		try {
			IoAcceptor acceptor = new SocketAcceptor();
	        IoAcceptorConfig config = new SocketAcceptorConfig();
	        acceptor.bind(
                new InetSocketAddress(DEFAULT_SERVER_PORT),
                new ServerSessionHandler(USE_CUSTOM_CODEC),
                config
            );
			log.info("Listening on port " + DEFAULT_SERVER_PORT);
		} catch (Exception e) {
			log.error(e, e);
			return false;
		}
		return true;
	}

	public static void main(String[] args) {
		processClassPath();
    	TempServerDatabase.fillValues();
		Server server = new Server();
		server.start();
	}
	
	private static void processClassPath() {
		String libFolder = System.getProperty("embedchat.lib.dir");
		if (libFolder != null) {
			File libDirectory = new File(libFolder);
			if (libDirectory.exists()) {
				try {
					ClassPathHacker.addFile(libDirectory);
				} catch (IOException e) {
					e.printStackTrace();
				}				
			}
		}
	}
}
